package com.lp.sys.controller;

import java.io.IOException;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.iframework.commons.domain.enums.HttpStatusCode;
import org.iframework.commons.util.fast.L;
import org.iframework.commons.util.fast.V;
import org.iframework.support.spring.cache.api.BaseCacheManager;
import org.iframework.support.spring.controller.BaseControllerSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.lp.business.domain.JsonResultModel;
import com.lp.business.model.Access;
import com.lp.business.model.Menu;
import com.lp.business.model.User;
import com.lp.business.service.AccessService;
import com.lp.business.service.MenuMethodService;
import com.lp.business.service.MenuService;
import com.lp.business.service.UserService;

/**
 * 系统后台登录、注销、首页、登录控制器
 * 
 * @author fanjunjian
 * 
 */
@Controller
@RequestMapping("/admin/index")
public class IndexController extends BaseControllerSupport{
	@Autowired(required = true)
	private AccessService accessService;
	@Resource(name = "userService")
	private UserService userService;
	@Resource(name = "menuService")
	private MenuService menuService;
	@Resource(name = "menuMethodService")
	private MenuMethodService menuMethodService;
	@Resource(name = "baseCacheManager")
	private BaseCacheManager cacheManager;

	/**
	 * 进入后台首页
	 */
	@RequestMapping(value = "index", method = { RequestMethod.POST, RequestMethod.GET })
	public String index(HttpServletRequest request, HttpServletResponse response, Model model) {
		String mobile = (String) request.getAttribute("mobile");
		mobile = (String) request.getSession().getAttribute("mobile");
		User u = (User) cacheManager.loadObject(mobile + "_settlement_adminSessionInfo");
		if (u != null) {
			model.addAttribute("userId", u.getId());
			model.addAttribute("loginName", u.getLoginName());
			model.addAttribute("userName", u.getUserName());
			model.addAttribute("roles", u.getRoles());
			List<Access> accesses = this.accessService.getUserAccessList(u);
			List<Menu> menus = this.menuService.getUserMenuList(accesses);
			model.addAttribute("menuList", menus);
		} else {
			u = this.userService.findUserByMoible(mobile);
			if (u == null) {
				Cookie cookie = new Cookie("memcacheSessionKeySettlement", null);
				cookie.setMaxAge(0);
				cookie.setPath("/");
				response.addCookie(cookie);
				return "/frame/error";
			}
			model.addAttribute("userId", u.getId());
			model.addAttribute("loginName", u.getLoginName());
			model.addAttribute("userName", u.getUserName());
			model.addAttribute("roles", u.getRoles());
			List<Access> accesses = this.accessService.getUserAccessList(u);
			List<Menu> menus = this.menuService.getUserMenuList(accesses);
			cacheManager.cacheObject(mobile + "_settlement_adminSessionInfo", u, 1800L);
			cacheManager.cacheObject(mobile + "_settlement_accessSessionInfo", accesses, 1800L);
			model.addAttribute("menuList", menus);
		}
		request.getSession().setAttribute("adminSessionInfo", u);
		return "/frame/index";

	}

	@RequestMapping(value = "home", method = { RequestMethod.POST, RequestMethod.GET })
	public String home(HttpServletRequest request, Model model) {
		String mobile = (String) request.getAttribute("mobile");
		User u = (User) cacheManager.loadObject(mobile + "_settlement_adminSessionInfo");
		// User u = (User)
		// request.getSession().getAttribute("adminSessionInfo");
		if (V.isNotEmpty(u)) {
			u.setLoginPwd(null);
		}

		model.addAttribute("user", u);
		return "/frame/home";

	}

	@RequestMapping(value = "shouye", method = { RequestMethod.POST, RequestMethod.GET })
	public String shouye(HttpServletRequest request, Model model) {
		User u = (User) request.getSession().getAttribute("adminSessionInfo");
		model.addAttribute("userId", u.getId());
		model.addAttribute("LoginName", u.getLoginName());
		model.addAttribute("userName", u.getUserName());
		model.addAttribute("roles", u.getRoles());
		return "/frame/shouye";

	}

	/**
	 * 验证用户合法性
	 */
	@RequestMapping(value = "checkLogin", method = { RequestMethod.POST })
	public void checkLogin(HttpServletRequest request, HttpServletResponse response, String loginName,
			String loginPwd) {
		try {
			if (V.isEmpty(loginName)) {
				renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "帐号格式非法").toSysJsonString(), response);
				return;
			}
			if (!this.userService.isExistsLoginName(loginName)) {
				renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "账号不存在").toSysJsonString(), response);
				return;
			}
			if (V.isEmpty(loginPwd)) {
				renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "密码格式非法").toSysJsonString(), response);
				return;
			}
			User user = this.userService.findUserByLoginNameAndLoginPwd(loginName, loginPwd);
			if (user == null) {
				renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "密码错误").toSysJsonString(), response);
				return;
			}
			String mobile = user.getMobile();
			request.getSession().setAttribute("mobile", mobile);
			request.getSession().setAttribute("adminSessionInfo", user);
			String sessionId = "settlement";
			Cookie cookies[] = request.getCookies();
			String uuid = "";
			if (cookies != null && cookies.length > 0) {
				for (int i = 0; i < cookies.length; i++) {
					if (cookies[i].getName().equals(sessionId)) {
						L.i(cookies[i].getName());
						uuid = cookies[i].getValue();
					}
				}
			}

			if ("".equals(uuid)) {
				L.i("添加cookie到浏览器，缓存（adminSessionInfo，accessSessionInfo）对象到memcache");
				uuid = java.util.UUID.randomUUID().toString();
				Cookie mycookies = new Cookie(sessionId, uuid);
				mycookies.setMaxAge(1800);
				mycookies.setPath("/");
				response.addCookie(mycookies);
				cacheManager.cacheObject(uuid, mobile, 1800L);
			}
			
			renderJson(new JsonResultModel(HttpStatusCode.SUCCESS.getDesc(), "成功").toSysJsonString(), response);
		} catch (Exception e) {
			L.e(e.getMessage(), e);
			renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "系统繁忙，请稍候再试").toSysJsonString(), response);
		}
	}

	/**
	 * 进入登录页面
	 */
	@RequestMapping(value = "login", method = { RequestMethod.POST, RequestMethod.GET })
	public String login(HttpServletRequest request, HttpServletResponse response) {
		return "/login/index";
	}

	/**
	 * 退出后台系统
	 * @return 
	 */
	@RequestMapping(value = "logout", method = { RequestMethod.POST, RequestMethod.GET })
	public String logout(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 登出系统后台
		clearAuthorizeSession(request,response);
		clearAccessSession(request,response);
		request.getSession().invalidate();
		//response.sendRedirect(ssoLogoutUrl);
		return "/login/index";
	}

	/**
	 * 清除session
	 * 
	 * @throws IOException
	 */
	@RequestMapping(value = "clear", method = { RequestMethod.POST, RequestMethod.GET })
	public void clear(HttpServletRequest request,HttpServletResponse response) throws IOException {
		try {
			clearAuthorizeSession(request,response);
			clearAccessSession(request,response);
			request.getSession().invalidate();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 
	 */
	@RequestMapping(value = "clearAuthorizeSession", method = { RequestMethod.POST, RequestMethod.GET })
	public void clearAuthorizeSession(HttpServletRequest request, HttpServletResponse response) {
		// 清理登入session缓存
		HttpSession session = request.getSession();
		session.removeAttribute("adminSessionInfo");
		//renderJson(new JsonResultModel(HttpStatusCode.SUCCESS.getDesc(), "session缓存清理成功").toSysJsonString(), response);
	}

	/**
	 * 
	 */
	@RequestMapping(value = "clearAccessSession", method = { RequestMethod.POST, RequestMethod.GET })
	public void clearAccessSession(HttpServletRequest request, HttpServletResponse response) {
		// 清理权限缓存
		HttpSession session = request.getSession();
		session.removeAttribute("accessSessionInfo");
		session.removeAttribute("accessMenuSessionInfo");
		//renderJson(new JsonResultModel(HttpStatusCode.SUCCESS.getDesc(), "session缓存清理成功").toSysJsonString(), response);
	}

//	/**
//	 * 输出验证码图片
//	 */
//	@RequestMapping(value = "imgCode", method = { RequestMethod.POST, RequestMethod.GET })
//	public void imgCode(HttpServletRequest request, HttpServletResponse response) {
//		// 设置相应类型,告诉浏览器输出的内容为图片
//		response.setContentType("image/jpeg");
//		// 设置响应头信息，告诉浏览器不要缓存此内容
//		response.setHeader("Pragma", "No-cache");
//		response.setHeader("Cache-Control", "no-cache");
//		response.setDateHeader("Expire", 0);
//		CaptchaUtils captchaUtils = new CaptchaUtils();
//		try {
//			captchaUtils.getRandcode(request, response);// 输出图片方法
//		} catch (Exception e) {
//			L.e(e.getMessage(), e);
//		}
//	}
}
